package cn.liccshop.sys.utils;

import cn.liccshop.sys.constants.Constants;
import cn.liccshop.sys.exception.MySystemException;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

/**
 * @author LiCC
 * @program LiCCShop
 * @description 高德地图API接口
 * @since 2019-05-06-22:55
 */
public class GaoDeUtil {
    public static JSONObject getAddressInfo(String keywords, int subdistrict) throws MySystemException {
        if (StringUtils.isBlank(keywords)){
            /** 城市编号为空 **/
            throw new MySystemException("城市编号参数异常", Constants.INVALID_PARM);
        }
        if (subdistrict<0 || subdistrict>3){
            /** 下级行政区级数 **/
            throw new MySystemException("下级行政区级数参数异常", Constants.INVALID_PARM);
        }
        JSONObject jsonObject = null;
        String apiUrl = Constants.GAODE_API_URL + "?key=" + Constants.GAODE_API_KEY + "&keywords=" + keywords + "&subdistrict=" + subdistrict;
        try {
            System.out.println(apiUrl);
            URL url = new URL(apiUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
            String line;
            StringBuffer stringBuffer = new StringBuffer();
            while((line = in.readLine()) != null){
                stringBuffer.append(line);
            }
            in.close();
            jsonObject = (JSONObject) JSONObject.parse(stringBuffer.toString());
        } catch (MalformedURLException e) {
            e.printStackTrace();
            throw new MySystemException("高德第三方接口连接失败",Constants.SERVICE_FAIL);
        } catch (IOException e) {
            e.printStackTrace();
            throw new MySystemException("地从高德获取的数据处理失败",Constants.SERVICE_FAIL);
        }
        return jsonObject;
    }

}
